﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Luna.Data.SqlCe
{
    public class LunaDatabaseAdapter : SqlCeDatabaseAdapter
    {
        private const string REQUEST_REGEX = ".([a-zA-Z_]*?).sql";
        private const string FILE_NAME = "database.sdf";
        private const string DEFAULT_NAMESPACE = "Luna.Data.SqlCompact.";

        private Dictionary<string, string> _Requests;

        private static object _RequestLock = new object();

        protected override string GetRequest(string P_CommandName)
        {
            lock (_RequestLock)
            {
                if (_Requests == null)
                {
                    // load requests
                    Assembly L_Assembly = Assembly.GetExecutingAssembly();
                    string[] L_ResourcesNames = L_Assembly.GetManifestResourceNames();
                    _Requests = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);

                    Regex L_RegEx = new Regex(REQUEST_REGEX);

                    foreach (string L_ResourceName in L_ResourcesNames)
                    {
                        if (L_RegEx.IsMatch(L_ResourceName))
                        {
                            Stream L_File = L_Assembly.GetManifestResourceStream(L_ResourceName);
                            StreamReader L_Reader = new StreamReader(L_File);

                            _Requests[L_RegEx.Match(L_ResourceName).Groups[1].Value] = L_Reader.ReadToEnd();
                            L_Reader.Close();
                        }
                    }
                }

                if (_Requests.ContainsKey(P_CommandName))
                {
                    return _Requests[P_CommandName];
                }
                else
                {
                    throw BuildErrorFormat<ArgumentException>("Unavailable request {0} on {1}", P_CommandName, this.DataSourceDescription);
                }
            }
        }

        public override bool Initialized
        {
            get { return File.Exists(FILE_NAME); }
        }

        public override void Initialize()
        {
            if (Initialized)
            {
                File.Delete(FILE_NAME);
            }

            FileStream L_Stream = null;
            try
            {
                L_Stream = File.Create(FILE_NAME);
                Stream L_File = Assembly.GetExecutingAssembly().GetManifestResourceStream(DEFAULT_NAMESPACE + FILE_NAME);
                L_File.CopyTo(L_Stream);
                L_Stream.Close();
                L_File.Close();
            }
            catch (Exception)
            {
                if (L_Stream != null)
                {
                    L_Stream.Dispose();
                }

                throw;
            }
        }
    }
}
